import json
import websocket
import threading

from config.Settings import WebSocket


class XiaoYuQQBotSDK:
    def __init__(self, ws_url: str):
        self._ws_url = ws_url
        self._ws_client = None

    def _on_open(self, ws):
        print("WebSocket connection opened.")

    def _on_close(self, ws, close_status_code, close_msg):
        print("WebSocket connection closed. Reconnecting...")
        # 尝试重新连接
        self.connect()

    def connect(self):
        self._ws_client = websocket.WebSocketApp(
            self._ws_url,
            on_open=self._on_open,
            on_close=self._on_close
        )
        # 使用线程运行 WebSocket 客户端
        threading.Thread(target=self._ws_client.run_forever).start()

    def send_message(self, target_qq, message):
        if not self._ws_client:
            print("WebSocket client is not connected.")
            return
        self._ws_client.send(json.dumps({
            "action": "send_msg",
            "params": {
                "user_id": target_qq,
                "message": message
            }
        }))


if __name__ == '__main__':

    xiao = XiaoYuQQBotSDK(WebSocket.url)
    xiao.connect()  # 启动 WebSocket 连接

    # 等待连接成功后再发送消息
    import time

    time.sleep(2)  # 延迟 2 秒，确保连接已建立

    xiao.send_message('705301804', 'test')  # 发送私聊消息
